<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin_user extends CI_Controller
{
	public $data = array();
	
        function __construct() {
       
            parent::__construct();
            $this->load->model('user_model');
            // Load library
            $this->load->library('form_validation');
//			$is_logged_in = $this->session->userdata('user_id')?$this->session->userdata('user_id'):'';
//        	if ($is_logged_in) redirect('admin');

        }
   
	
    // Retrieve
	function index($offset = 0)
	{
	    $this->load->library('pagination');
	    
	    $perpage = 1;
	    
	    $config['base_url'] = base_url() . 'users/index/';
	    $config['total_rows'] = $this->user_model->user_info(array('count' => true));
	    $config['per_page'] = $perpage;
	    $config['uri_segment'] = 3;
	    
	    $this->pagination->initialize($config);
	    
	    $data['pagination'] = $this->pagination->create_links();
	    
            $data['users'] = $this->user_model->user_info(array('limit' => $perpage, 'offset' => $offset));
		
            $this->load->view('users/users_index', $data);
	}
	
	// Update
	function edit()
	{
            $user_id = $this->input->post('user_id');
	    $data['user'] = $this->user_model->user_info(array('user_id' => $user_id));
	    if(!$data['user']) redirect('users');

	    // Validate form
	    $this->form_validation->set_rules('user_email', 'user_email', 'trim|required|valid_email');
	    $this->form_validation->set_rules('user_password', 'user_password', 'trim|min_length[6]');
	    $this->form_validation->set_rules('user_group_id', 'user_group_id', 'trim|required');
	    $this->form_validation->set_rules('user_status', 'user_status', 'trim|required');
	    
	    if($this->form_validation->run())
	    {
	        
	        if($this->user_model->user_update($this->input->post()))
	        {
	            $this->session->set_flashdata('flashConfirm', 'The user has been successfully updated.');
	            redirect('users');
	        }
	        else
	        {
                $this->session->set_flashdata('flashError', 'A database error has occured, please contact your administrator.');
	            redirect('users');
	        }
	    }
	    
	    $this->load->view('users/users_edit_form', $data);
	}
	
	// Delete
	function delete($user_id)
	{
	    $data['user'] = $this->user_model->user_info(array('user_id' => $user_id));
	    if(!$data['user']) redirect('users');
	    
	    $this->user_model->user_update(array(
	        'user_id' => $user_id,
	        'user_status' => '0'
	    ));
	    
	    $this->session->set_flashdata('flashConfirm', 'The user has been successfully deleted.');
	    redirect('users');
	}
	
	function login()
	{
                    
		if ($this->input->post())
		{
			// Validation data request
			$this->form_validation->set_rules('user_email', 'email', 'trim|required|valid_email');
			$this->form_validation->set_rules('user_password', 'password', 'trim|required');
                        
			
			if($this->form_validation->run())
			{
				// the form has successfully validated
				if($this->user_model->user_login(array('user_email' => $this->input->post('user_email'), 'user_password' => $this->input->post('user_password'))))
				{
                                        $return = $this->input->post('return');
					if($return) redirect ($return);
                                        else  redirect ('admin');
				} 
				
			}
			
			$this->session->set_flashdata('Error', 'Login error.');
			
		}
		$this->data['title'] = "Login page";
		$this->load->view('users/users_login_form', $this->data)	;
		
	}
	
	public function logout($return = '')
	{
		// Clear session
	    $this->session->sess_destroy();
            if($return)
	    redirect($return);
            else redirect ('admin_user/login');
	}
	
        public function ajax_user_get_all()
        {
            $query = $this->db->query('SELECT u.user_id, u.user_group_id, u.user_name, u.user_email, g.group_name AS user_group, u.user_last_visited, u.user_status
            				  		   FROM '.$this->db->dbprefix.'users AS u INNER JOIN '.$this->db->dbprefix.'group_users AS g ON g.group_id=u.user_group_id 
            				  		   WHERE g.group_published=1');
            
            
			$this->ajax_response( $query->result_array());
        }
        
        public function ajax_user_group_get_all()
        {
            $query = $this->db->query('SELECT group_id, group_name
            				  		   FROM '.$this->db->dbprefix.'group_users
            				  		   WHERE group_published=1');
            
            
			$this->ajax_response( $query->result_array());
        }
        
        public function ajax_user_add()
        {
        	 $this->form_validation->set_rules('user_email', 'user_email', 'trim|required|valid_email');
	    	 $this->form_validation->set_rules('user_password', 'user_password', 'trim|required|min_length[6]');
	    	 $this->form_validation->set_rules('user_group_id', 'user_group_id', 'trim|required');
	    	 $this->form_validation->set_rules('user_status', 'user_status', 'trim|required');
	    	 
	    	  if($this->form_validation->run())
			    {
			        // Validation passes
			        $user_id = $this->user_model->user_add($this->input->post());
			        
			        if($user_id)
			        {
			            $this->ajax_response(array('success'=>'true', 'msg'=>'The user has been successfully added'));
			        }
			        else
			        {
		               
			        }
			    }
	    	 
        }
        
        public function ajax_user_update()
        {
        	 $this->form_validation->set_rules('user_email', 'user_email', 'trim|required|valid_email');
	    	 //$this->form_validation->set_rules('user_password', 'user_password', 'trim|required|min_length[6]');
	    	 $this->form_validation->set_rules('user_group_id', 'user_group_id', 'trim|required');
	    	 $this->form_validation->set_rules('user_status', 'user_status', 'trim|required');
	    	 
	    	  if($this->form_validation->run())
			    {
			        // Validation passes
			        $user_id = $this->user_model->user_update($this->input->post());
			        
			        if($user_id)
			        {
			            $this->ajax_response(array('success'=>'true', 'msg'=>'The user has been successfully added'));
			        }
			        else
			        {
		               
			        }
			    }
        }
        
        public function ajax_response( $response )
        {
        	header('Cache-Control: no-cache, must-revalidate');
			header('Expires: '.gmdate('D, d M Y H:i:s', time() + 10 ).' GMT');
			header('Content-type: application/json');
			
			echo json_encode($response);
			exit();
        }
}